<template>
    <el-form
        :model="login_form"
        label-width="65px"
        :rules="login_rules"
        ref="login_form"
        class="login-form"
        size="small"
    >
        <el-form-item prop="email" label="邮箱">
            <el-input type="email" v-model.trim="login_form.email"> </el-input>
        </el-form-item>
        <el-form-item prop="password" label="密码">
            <el-input
                type="password"
                v-model.trim="login_form.password"
                maxlength="16"
                show-password
                @keyup.enter="handle_login"
            >
            </el-input>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="handle_login">登录</el-button>
            <el-button type="danger" @click="handle_reset">重置</el-button>
        </el-form-item>
    </el-form>
</template>

<script>
export default {
    data() {
        return {
            login_form: {
                email: "",
                password: ""
            },
            login_rules: {
                email: [
                    {
                        required: true,
                        message: "请填写邮箱",
                        trigger: "blur" // 默认是 input
                    },
                    {
                        type: "email",
                        message: "请填写正确的邮箱",
                        trigger: "blur"
                    }
                ],
                password: [
                    {
                        required: true,
                        message: "请填写密码",
                        trigger: "blur"
                    },
                    {
                        min: 6,
                        max: 16,
                        message: "密码长度在6~16之间",
                        trigger: "blur"
                    }
                ]
            }
        }
    },
    methods: {
        handle_login() {
            this.$refs.login_form.validate(async (valid) => {
                if (valid) {
                    const { email, password } = this.login_form
                    const result = await this.$store.dispatch("user/user_login", { email, password })
                    // 登录成功，跳转首页
                    if (result) {
                        const path = this.$route.query.target_url || "/"
                        this.$router.push(path)
                    } else {
                        this.$message({
                            message: result,
                            type: 'error'
                        })
                    }
                }
            })
        },
        handle_reset() {
            this.$refs.login_form.resetFields()
        }
    }
}
</script>
